package com.wf.filter;


import cn.hutool.json.JSONUtil;
import com.wf.domain.SysUser;
import com.wf.propertity.JwtProperties;
import com.wf.utils.JwtUtil;
import com.wf.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * jwt令牌校验的拦截器
 * @author wfyn
 */

@Slf4j
@Component
public class JwtTokeFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    RedisUtil redisUtil;


    /**
     * 校验jwt
     **/
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {


        String token = request.getHeader(jwtProperties.getAdminTokenName());

        if (!StringUtils.hasText(token) ) {
            filterChain.doFilter(request, response);
            return;
        }
        String userId;
        try {

            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token.replace("Bearer ", ""));
            userId = claims.get("userId").toString();

        }
        catch (Exception e) {
            throw new RuntimeException("token非法");
        }
//       SecureUser secureUser =(SecureUser) redisUtil.get("login:" + userId);
//        log.info("{}",secureUser.toString());
        Object object =  redisUtil.get("login:" + userId);

        SysUser user = JSONUtil.toBean(object.toString(), SysUser.class);
        if (Objects.isNull(user) ) {
            throw  new RuntimeException("用户未登录");
        }
        Collection<String> authoritiesCopy = user.getAuthoritiesCopy();
        List<SimpleGrantedAuthority> authoritySet = new ArrayList<>();
        for (String power : authoritiesCopy) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(power);
            authoritySet.add(authority);
        }
        user.setAuthorities(authoritySet);


        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(user,
                null, user.getAuthorities()
        ));

        filterChain.doFilter(request, response);



    }
}
